<template>
    <view class="container">
        <custom-nav></custom-nav>
        <view style="margin-top: 120rpx">
            <view class="top-bar dl-flex center p-y-4">
                <main-switch :data="currentCategory" @change="handleCategory"></main-switch>
            </view>
        </view>

        <pet-avatar ref="pet" @click="handlePetClick" :message="messages[0]"></pet-avatar>
        <!-- 日历组件 -->
        <view class="calendar-section">
            <Calendar  @change="handleMonthChange" @select="handleSelect" :insert="true" :data="recordMap[currentCategory]" />
        </view>
        <view style="display: flex; justify-content: center; gap: 10px; margin: 20px">
            <view class="menu checkin-menu dl-flex center" @tap="handleCard('share')">
                <text class="tn-icon-flower-fill"></text>
                <text class="menu-label">每日打卡</text>
            </view>
            
            <view class="menu main-menu dl-flex center" @tap="handleCard('data')">
                <text class="tn-icon-data"></text>
                <text class="menu-label">数据统计</text>
            </view>
        </view>
        <tn-popup closeBtn mode="bottom" :borderRadius="24" v-model="popShow" :safeAreaInsetBottom="true">
            <view class="content">
                <view class="card-title">{{ currentCategory == 'weight' ? '体重记录' : '睡眠记录' }}</view>
                <view class="sleep-card">
                    <view class="sleep-status">
                        <text class="status-text">{{ currentRecord.is_today ? '今日记录' : currentRecord.full_date }}</text>
                        <view class="sleep-time">
                            <tn-input
                                :placeholder="`${currentCategory == 'weight' ? '请输入记录，单位:公斤' : '请输入记录，单位:小时'}`"
                                v-model="currentRecord.data"
                                type="digit"
                                border
                            />
                        </view>
                    </view>
                    <view class="action-button" @click="addRecord">
                        {{ '确定' }}
                    </view>
                </view>
            </view>
        </tn-popup>

        <!-- 统计组件 -->
        <!-- <view class="stats-section">
            <view class="section-title">本月统计</view>
            <view class="stats-grid">
                <view class="stat-item">
                    <text class="stat-value">{{ averageSleepTime }}</text>
                    <text class="stat-label">平均睡眠时间</text>
                </view>
                <view class="stat-item">
                    <text class="stat-value">{{ totalSleepDays }}</text>
                    <text class="stat-label">总睡眠天数</text>
                </view>
                <view class="stat-item">
                    <text class="stat-value">{{ weeklyProgress }}%</text>
                    <text class="stat-label">本周进度</text>
                </view>
            </view>
        </view> -->
    </view>
</template>

<script>
import { formatDate, upMessage, downMessage, helloMessage } from '@/store/utils';
const record = uniCloud.importObject('record', {
    customUI: true
});
export default {
    data() {
        return {
            currentYear: 0,
            currentMonth: 0,
            isSleeping: false,
            sleepStartTime: null,
            sleepEndTime: null,
            popShow: false,
            todaySleepDuration: null,
            averageSleepTime: '7.5h',
            weeklyProgress: 85,
            totalSleepDays: 30,
            lastDate: {},
            messages: [],
            recordMap: {
                weight: [],
                sleep: [],
                cost: []
            },
            currentRecord: {
                data: '',
                full_date: ''
            },
            currentCategory: 'weight', // 当前分类，默认为体重
            weight: '',
           
            tabsIndex: 0,
            swiperIndex: 0
        };
    },
    onLoad() {
        
        uni.$on('refresh', () => {
            this.loadData(formatDate(new Date(this.currentYear, this.currentMonth, 0), 'yyyy-MM'));
        });
    },

    methods: {
        handleCard(type) {
            if (type == 'share') {
                uni.navigateTo({
                    url: '/pages/poster/poster'
                });
            } else if (type == 'food') {
                uni.navigateTo({
                    url: '/subPages/food/index'
                });
            } else if (type == 'data') {
                uni.navigateTo({
                    url: `/pages/detail/detail?type=${this.currentCategory}&month=${this.currentMonth}&year=${this.currentYear}`
                });
            }
        },
        talk() {
            this.$refs.pet.startTalking();
        },
        initData(month) {
            const user = uni.getStorageSync('user');
            if (user) {
                this.loadData(month);
            }
            var data = upMessage();
            this.messages = [`${data.emoji}，${data.text}`];
        },
        handleMonthChange(year, month) {
            this.currentYear = year;
            this.currentMonth = month;
            this.initData(formatDate(new Date(year, month, 0), 'yyyy-MM'));
        },

        recordTrend(records) {
            if (!records || records.length < 2) return null;

            // 按日期排序
            records.sort((a, b) => new Date(a.full_date) - new Date(b.full_date));

            // 获取最近两条记录
            const latestRecord = records[records.length - 1];
            const previousRecord = records[records.length - 2];

            // 计算差值
            const difference = latestRecord.data - previousRecord.data;
            const trend = {
                type: difference > 0 ? 'up' : 'down',
                difference: Math.abs(difference).toFixed(1),
                latestDate: latestRecord.full_date,
                previousDate: previousRecord.full_date,
                latestValue: parseFloat(latestRecord.data).toFixed(1),
                previousValue: parseFloat(previousRecord.data).toFixed(1)
            };

            if (trend.type == 'up') {
                var data = upMessage();
                this.messages = [`${data.emoji}，${data.text}`];
            } else {
                var data = downMessage();
                this.messages = [`${data.emoji}，${data.text}`];
            }
            this.talk();
            return trend;
        },

        handlePetClick() {
            var data = helloMessage();
            this.messages = [data.emoji + '，' + data.text];

            this.talk();
        },
        change(index) {
            this.current = index;
        },
        transform(data) {
            var temp = {
                weight: [],
                sleep: [],
                calories: [],
                cost: []
            };
            // 2. 按full_date升序排序并添加prev_date指针
            data.forEach((item) => {
                temp[item.category].push(item);
            });

            Object.keys(temp).forEach((category) => {
                temp[category].sort((a, b) => new Date(a.full_date) - new Date(b.full_date));
                temp[category].forEach((item, index) => {
                    item.prev_date = index > 0 ? temp[category][index - 1].full_date : null;
                });
            });
            return temp;
        },
        handleCategory(data) {
            this.currentCategory = data.value;
            this.recordTrend(this.recordMap[this.currentCategory]);
        },
        handleSelect(day, data) {
            if (this.currentCategory == 'calories') {
                uni.navigateTo({
                    url: `/subPages/food/index?type=${this.currentCategory}&full=${day.fullDate}`
                });
            } else {
                this.popShow = true;
                this.currentRecord = {
                    data: data ? data.data : '',
                    is_today: formatDate(new Date(), 'yyyy-MM-dd') == day.fullDate,
                    full_date: day.fullDate
                };
            }
        },
        // 加载睡眠数据
        loadData(month) {
            const user = uni.getStorageSync('user');
            record
                .queryRecord({
                    user_id: user._id,
                    month_date: month
                })
                .then((res) => {
                    this.recordMap = this.transform(res.data);
                    this.recordTrend(this.recordMap[this.currentCategory]);
                });
        },
        // 开始或结束睡眠
        toggleSleep() {
            if (!this.isSleeping) {
                // 开始睡眠
                this.sleepStartTime = new Date();
                this.isSleeping = true;
                const newRecord = {
                    startTime: this.sleepStartTime.toISOString(),
                    endTime: null
                };
                this.sleepRecords.push(newRecord);
            } else {
                // 结束睡眠
                this.sleepEndTime = new Date();
                this.isSleeping = false;
                const lastRecord = this.sleepRecords[this.sleepRecords.length - 1];
                lastRecord.endTime = this.sleepEndTime.toISOString();
                this.todaySleepDuration = this.calculateDuration(this.sleepStartTime, this.sleepEndTime);
            }
            // 保存数据
            this.saveSleepData();
        },
        // 保存睡眠数据
        saveSleepData() {
            try {
                uni.setStorageSync('sleepRecords', JSON.stringify(this.sleepRecords));
            } catch (e) {
                console.error('保存睡眠数据失败:', e);
            }
        },
        // 计算睡眠时长
        calculateDuration(startTime, endTime) {
            return Math.round((endTime - startTime) / (1000 * 60)); // 返回分钟数
        },
        // 格式化时长显示
        formatDuration(minutes) {
            const hours = Math.floor(minutes / 60);
            const mins = minutes % 60;
            return `${hours}小时${mins}分钟`;
        },
        // 格式化时间显示
        formatTime(date) {
            return date.toLocaleTimeString('zh-CN', { hour12: false });
        },

        async addRecord() {
            const user = uni.getStorageSync('user');
            console.log('user', user);
            if (user) {
                await record.createRecord({
                    user_id: user._id,
                    category: this.currentCategory,
                    data: this.currentRecord.data,
                    month_date: formatDate(new Date(this.currentRecord.full_date), 'yyyy-MM'),
                    full_date: this.currentRecord.full_date
                });
                uni.showToast({
                    title: '添加成功'
                });
                this.popShow = false;
                this.loadData(formatDate(new Date(this.currentYear, this.currentMonth, 0), 'yyyy-MM'));
            } else {
                uni.navigateTo({
                    url: '/pages/login/login'
                });
            }
        }
    }
};
</script>

<style lang="scss">
.menu {
    padding: 10rpx 20rpx;
    height: 80rpx;
    background: #fff;
    border-radius: 8rpx;
    box-shadow: 6px 6px 10px -1px rgba(0, 0, 0, 0.15), -6px -6px 10px -1px rgba(255, 255, 255, 0.7);
    color: $brand-color;
    font-size: 40rpx;
    .menu-label {
        font-size: 24rpx;
        margin-left: 10rpx;
    }
}

.container {
    min-height: 100vh;
    background-color: #f8f9fc;
    padding-bottom: 40rpx;
}

.status-bar {
    background-color: #fff;
    padding-top: env(safe-area-inset-top);
    .title {
        font-size: 36rpx;
        font-weight: bold;
        color: #333;
    }
}

.sleep-card {
    height: 55vh;
    background-color: #fff;
    padding: 40rpx;
    .sleep-status {
        margin-bottom: 32rpx;
        .status-text {
            font-size: 32rpx;
            font-weight: bold;
            margin-bottom: 32rpx;
            display: block;
        }
        .sleep-time {
            font-size: 48rpx;
            font-weight: bold;
            color: #333;
            display: block;
        }
    }

    .action-button {
        background-color: #5b67ca;
        color: #fff;
        text-align: center;
        padding: 18rpx;
        border-radius: 12rpx;
        font-size: 28rpx;
        font-weight: 500;
    }
}

.calendar-section,
.stats-section {
    border-radius: 24rpx;
    .section-title {
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
        margin-bottom: 24rpx;
    }
}
.stats-section {
    margin: 16rpx 32rpx;
    background-color: #fff;
    border-radius: 24rpx;
    padding: 40rpx;
    box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.08);
}

.stats-grid {
    display: flex;
    justify-content: space-between;

    .stat-item {
        text-align: center;
        flex: 1;

        .stat-value {
            font-size: 36rpx;
            font-weight: bold;
            color: #5b67ca;
            display: block;
            margin-bottom: 8rpx;
        }

        .stat-label {
            font-size: 24rpx;
            color: #666;
        }
    }
}
.card-title {
    display: flex;
    justify-content: center;
    height: 40px;
    line-height: 40px;
    font-weight: bold;
}
</style>
